import cplex
import cplex.callbacks as CPX_CB
import random
import numpy as np
#from instances import fscplex
from fscplex import fscplex
from callbacks import CheckBounds

NI = 30
NS = 30
step = 0.1

# Generate instances and read in parameters
fc = fscplex()
fc.generate_instance(NI, NS)

fc.write("fc_org.lp")
fc.parameters.read_file('../param/stofac.prm')
# Solve the original model

fc.solve()
true_v_sol   = fc.solution.get_values(fc.v_name)
true_obj_val = fc.solution.get_objective_value()
true_num_nodes = fc.solution.progress.get_num_nodes_processed()

fc.get_hard_v_lower_bounds()
# Set initial bounds for v
fc.v_lb = [13]*NI
#fc.v_lb = [true_v_sol[i] + 0.1 for i in fc.I]
fc.variables.set_lower_bounds(zip(fc.v_name, fc.v_lb))

# Pass data structures to the callback function
# use the overrided register_callback function
fc.register_callback(CheckBounds)

iter = 0

# Start check and resolve procedure
while(iter < 200):
    print "----------------------"
    print "Iteration ", iter
    print "----------------------"
    iter += 1

    # resolve the problem
    fc.solve()
    if fc.flag[0] == 1: #pass all the test
        print "finish loop"
        print fc.solution.progress.get_num_nodes_processed()
        break
    
    elif fc.flag[0] == 0: #binding being checked
        # decreate the lower bound for v
        print fc.solution.progress.get_num_nodes_processed()
        fc.variables.set_lower_bounds(zip(fc.v_name, fc.v_lb))

"""
    else: # at the root node integer solution is found
        v_lb = [v_lb[i] - step for i in I]
        c.variables.set_lower_bounds(zip(v_name, v_lb))
        print c.variables.get_lower_bounds(v_name)
"""

fc.write("fc.lp")
print "\n------------------------"
print "last lower bound of v"
print "------------------------"
print np.array(fc.variables.get_lower_bounds(fc.v_name))
print "\n------------------------"
print "last v values"
print "------------------------"
print np.array(fc.solution.get_values(fc.v_name))
print "\n------------------------"
print "true v values"
print "------------------------"
print np.array(true_v_sol)
print "\n------------------------"
print "last objective value"
print "------------------------"
print fc.solution.get_objective_value()
print "\n------------------------"
print "true objective value"
print "------------------------"
print true_obj_val
print true_num_nodes

